/**
* @Description:（基于腾讯地图 ）关键选点定位地图返回位置组件
* @author NewLore1
* @Date 2021/10/05/14:57
* @LastEditors: 乔
* @LastEditTime: 2021/10/05/14:57
*第一步：申请腾讯地图key
*第二步：安装qqmap依赖：npm install qqmap --save
**/
<template>
<!--使用的是抽屉弹出-->
  <el-drawer
    :wrapperClosable="false"
    size="40%"
    title="位置选择"
    :visible.sync="showStatus"
    direction="rtl"
    width="600px">
    <!-- 搜索的表单-->
    <el-form style="margin-left: 20px" class="searchForm" size="small" :model="searchFrom">
      <el-row :gutter="5">
        <el-col :span="10">
          <el-form-item prop="name">
            <el-input clearable placeholder="请输入搜索位置信息"
                      v-model="searchFrom.name"
                      name="name"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-button icon="el-icon-search" type="primary" size="mini"
                     @click="searchAddress">搜索位置
          </el-button>
        <el-button icon="el-icon-location-information" type="primary" size="mini"
                   @click="getLocationByqqMap">定位当前
        </el-button>
        </el-col>
      </el-row>
    </el-form>
<!--  地图显示 注意id必须要加。因为下面会指定id加载地图-->
    <div id="mapContainer" style="width:100%;height:270px;"></div>
<!--    附近地点显示-->
    <el-table
      @row-click="rowClick"
      highlight-current-row
      :data="nearPointList"
      max-height="300"
      style="width: 100%">
      <el-table-column prop="name" label="附近地点名称">
        <template slot-scope="scope">
          <h1>{{scope.row.name}}</h1>
          <h7>{{scope.row.address}}</h7>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="130">
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click.native.prevent="selectAddress(scope.row)"
            icon="el-icon-check"
            size="small">
            确认选择
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-drawer>
</template>
<script>

/* 引入qqmap*/
import maps from 'qqmap'

export default {
  data() {
    return {
      qqMapKey:process.env.VUE_MAP_KEY,//地图key值
      isgetlocat:false,
      rootAddress: '',
      searchFrom: {name: ''},
      nearPointList: [],
      showStatus: false,
      map: '',
      data: '',
      markersArray: [],
    }
  },
  mounted() {
    // 初始化地图
    this.initMap();
    //获取定位
  /*  let getlocal = setInterval(()=>{
      //this.getLocationByqqMap()
      if(this.isgetlocat == true) { // 设置一个停止的标志变量
        clearInterval(getlocal);
      }
    }, 100);*/
  },
  created() {
    console.log(" 获取信息process.env.MAP_KEY: ",process.env)
    console.log(" 获取信息urlthis.qqMapKey: ",this.qqMapKey)
    console.log(" 获取信息urlthis.baseURL: ",this.baseURL)
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "https://mapapi.qq.com/web/mapComponents/geoLocation/v/geolocation.min.js";
    document.getElementsByTagName('head')[0].appendChild(script);
  },
  methods: {
    //定位当前位置,调用定位
    getLocationByqqMap(){
      let geolocation = new qq.maps.Geolocation(this.qqMapKey, "myapp")
      geolocation.getLocation(this.showPosition,this.showErr,{timeout: 2000})
      this.isgetlocat=true;
    },
    //定位成功
    showPosition(position) {
      let latLng = new qq.maps.LatLng(position.lat,position.lng);
      this.geocoder.getAddress(latLng);
    },
    //定位失败
    showErr(error) {
      console.log('定位失败：',error)
    },
    // 搜索地址
    searchAddress() {
      if (!this.searchFrom.name) {
        this.$message.error('未输入搜索内容')
        return
      }
      this.setLocationByAddress(this.searchFrom.name)
    },
    //点击行数据
    rowClick(row, event, column) {
      let latLng = new qq.maps.LatLng(row.latLng.lat,row.latLng.lng);
      this.geocoder.getAddress(latLng);
    },
    // 初始化地图
    initMap() {
      console.log("初始化地图");
      let that = this;
      maps.init(this.qqMapKey, () => {
        let latLon = new qq.maps.LatLng(34.769087,113.715313)
        let myOpts = {
          zoom: 14,
          center: latLon,
          mapTypeId: qq.maps.MapTypeId.ROADMAP
        }
        that.map = new qq.maps.Map(
          document.getElementById('mapContainer'),
          myOpts
        )
        qq.maps.event.addListener(that.map, 'click', function (event) {
          that.setLocationByLatLng(event.latLng.getLat(), event.latLng.getLng())
        });
      })
      // 经纬度解析类回调函数
      that.geocoder = new qq.maps.Geocoder({
        complete: function (result) {
          console.log("经纬度解析类回调函数result:",result)
          that.nearPointList = result.detail.nearPois
          that.map.setCenter(result.detail.location);
          let marker = new qq.maps.Marker({
            map: that.map,
            position: result.detail.location
          });
          that.markersArray.push(marker);
          if (that.markersArray.length > 1) {
            for (let i = 0; i < that.markersArray.length - 1; i++) {
              that.markersArray[i].setMap(null);// 清除标记
            }
          }
        }
      });
      // 地址解析回调函数
      that.geocoderLocation = new qq.maps.Geocoder({
        complete: function (result) {
          // 查找附近的点
          let latLng = new qq.maps.LatLng(result.detail.location.lat, result.detail.location.lng);
          that.geocoder.getAddress(latLng);
        }
      });



    },
    // 选择地址时间
    selectAddress(row) {
      console.log("确定选择地图row：",row)
      console.log("确定选择地图this.rootAddress：",this.rootAddress)
      let addName=row.address+row.name;
      this.$emit("on-select", addName, row.latLng.lat, row.latLng.lng)
      this.showStatus = false
    },
    // 父组件调用显示抽屉的方法
    show() {
      this.initMap()
      this.showStatus = true
    },
    // 父组件设置初始显示 省市区数据
    setLocationByAddress(address) {
      console.log("搜索关键字address：",address)
      this.rootAddress = address
      this.geocoderLocation.getLocation(address);
    },
    // 父组件设置初始显示 经纬度数据
    setLocationByLatLng(lat, lng) {
      let latLng = new qq.maps.LatLng(lat, lng);
      this.geocoder.getAddress(latLng);
    }

  }
}
</script>


